﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NewAndong.Comm
{
    public class CommonUtil
    {
        public static string ToJson<T>(T t)
        {
            try
            {
                return JsonConvert.SerializeObject(t);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 加载Json文件
        /// </summary>
        /// <typeparam name="T">Json映射类型</typeparam>
        /// <param name="path">文件路径</param>
        /// <param name="encoding">字符编码</param>
        /// <returns>数据对象</returns>
        public static T LoadJson<T>(string path, Encoding encoding)
        {
            try
            {
                using (StreamReader file = new StreamReader(path, encoding))
                {
                    string json = file.ReadToEnd();
                    var data = JsonConvert.DeserializeObject<T>(json);
                    return data;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 保存Json文件
        /// </summary>
        /// <typeparam name="T">Json映射类型</typeparam>
        /// <param name="path">文件路径</param>
        /// <param name="data">保存数据</param>
        public static void SaveJson<T>(string path, T data)
        {
            try
            {
                if (!File.Exists(path))  // 判断是否已有相同文件 
                {
                    FileStream fs1 = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
                    fs1.Close();
                }
                File.WriteAllText(path, JsonConvert.SerializeObject(data));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 把Json文本转为实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="input"></param>
        /// <returns></returns>
        public static T FromJSON<T>(string input)
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(input);
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }
    }
}
